import { _decorator } from 'cc';
const { ccclass, property } = _decorator;

// // @ccclass

// export default class ArrayUtils {
//         /**
//          * 随机打乱数组顺序（Fisher-Yates 洗牌算法）
//          * @param array 需要打乱的数组
//          */
//         public static shuffle<T>(array: T[]): T[] {
//             for (let i = array.length - 1; i > 0; i--) {
//                 const j = Math.floor(Math.random() * (i + 1));
//                 [array[i], array[j]] = [array[j], array[i]];
//             }
//             return array
//         }
//     }

export const ArrayUtils = {
    Count<T>(array: Array<T>, check: (a: T) => boolean): number {
        let n = 0;
        for (let i = 0; i < array.length; i++) {
            const element = array[i];
            if (check(element)) n++;
        }
        return n;
    },
    Remove<T>(array: Array<T>, element: T): boolean {
        const index = array.indexOf(element);
        if (index >= 0) {
            array.splice(index, 1);
            return true;
        };
        return false;
    },
    ToMap<T>(array: Array<T>, getkey: (arg: T) => string, out?: { [key: string]: T }): { [key: string]: T } {
        const _out: { [key: string]: T } = out || {};
        array.forEach(it => _out[getkey(it)] = it);
        return _out;
    },
    Flat<T, U>(array: Array<T>, action: (arg: T) => U): Array<U> {
        const newArr = [];
        array.forEach(it => newArr.push(action(it)));
        return newArr;
    },
    FindFirst<T>(array: Array<T>, action: (arg: T) => boolean): T {
        for (let i = 0; i < array.length; i++) {
            const element = array[i];
            if (action(element)) return element;
        }
        return null;
    },
    FindLast<T>(array: Array<T>, action: (arg: T) => boolean): T {
        for (let i = array.length - 1; i >= 0; i--) {
            const element = array[i];
            if (action(element)) return element;
        }
        return null;
    },
    Shuffle(array: Array<any>) {
        let index = -1,
            length = array.length,
            lastIndex = length - 1;
        let size = length;
        while (++index < size) {
            const rand = index + Math.floor(Math.random() * (lastIndex - index + 1))
            const value = array[rand];
            array[rand] = array[index];
            array[index] = value;
        }
    },
    ShuffleArray(array: Array<any>) {
        array.sort(() => Math.random() - 0.5);
    }
}